<?php
/**
 * @desc 支付宝.企业支付
 * @document https://docs.open.alipay.com/api_28/alipay.fund.trans.toaccount.transfer
 * @author Vincent
 */

namespace young\payment;

use young\Common;

class AliCompanyPay extends AliConfig
{
    /**
     * @param $data
     * @return string
     */
    public function run($data)
    {
        $this->setConfig($data['config']);
        return $this->handle($data['account'], $data['realname'], $data['order_sn'], $data['amount'], $data['remark']);
    }

    /**
     * @param $account 收款人账号
     * @param $realname 收款人真实姓名
     * @param $orderSn 商户订单号
     * @param $amount 支付金额
     * @param $remark 付款备注
     * @return string
     */
    private function handle($account, $realname, $orderSn, $amount, $remark)
    {
        $common = [];
        $common['app_id'] = $this->appId;
        $common['method'] = 'alipay.fund.trans.toaccount.transfer';
        $common['format'] = self::FORMAT;
        $common['charset'] = self::CHARSET;
        $common['sign_type'] = self::SIGN_TYPE;
        $common['timestamp'] = date('Y-m-d H:i:s', time());
        $common['version'] = self::VERSION;
        $common['biz_content'] = [];
        $common['biz_content']['out_biz_no'] = $orderSn;
        $common['biz_content']['amount'] = $amount;
        $common['biz_content']['payee_type'] = 'ALIPAY_LOGONID';
        $common['biz_content']['payee_account'] = $account;
        $common['biz_content']['payee_real_name'] = $realname;
        $common['biz_content']['remark'] = $remark;
        $common['biz_content'] = json_encode($common['biz_content'], JSON_UNESCAPED_UNICODE);
        $common = array_filter($common);

        ksort($common);

        $rsa2 = new AliRsa2;
        $key = $rsa2->getRsaKeyValue($this->rsaPrivateKey, 'private');
        $rsa2->setKey($key);
        $common['sign'] = $rsa2->encrypt(urldecode(http_build_query($common)));
        $common = $rsa2->splicingString($common);
        $result = Common::request_get(self::GETEWAY_URL . '?' . $common);
        $result = json_decode($result, true);
        $data = $result['alipay_fund_trans_toaccount_transfer_response'];

        //验证签名
        $rsa2->setKey($rsa2->getRsaKeyValue($this->aliPublicKey, 'public'));
        $verifySign = $rsa2->rsaVerify(json_encode($data, JSON_UNESCAPED_UNICODE), $result['sign']);

        if ($verifySign === true) {
            if ($data['code'] == '10000') {
                $result = ['error' => false, 'pay_sn' => $data['out_biz_no']];
                return $result;
            } else {
                throw new \Exception($data['sub_msg']);
            }
        } else {
            throw new \Exception('签名失败');
        }
    }
}